package io.wit.modules.wit.service.impl;

import io.wit.config.ConfigFile;
import io.wit.modules.sys.dao.SysUserDao;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.dao.SubjectDao;
import io.wit.modules.wit.entity.SubjectEntity;
import io.wit.modules.wit.service.SubjectService;
import io.wit.tool.ToolClient;
import io.wit.tool.ToolString;
import io.wit.tool.UploadFile;
import io.wit.tool.UploadObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("subjectService")
public class SubjectServiceImpl implements SubjectService {

    @Value("${upload_dir_window}")
    private String dir_window;

    @Value("${upload_dir_linux}")
    private String dir_linux;

    @Value("${role_value2}")
    private int roleValue2;

    @Autowired
	private SubjectDao subjectDao;

    @Autowired
    private SysUserDao sysUserDao;
	
	@Override
	public SubjectEntity queryObject(Long dataId){
		return subjectDao.queryObject(dataId);
	}
	
	@Override
	public List<SubjectEntity> queryList(Map<String, Object> map){
		return subjectDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return subjectDao.queryTotal(map);
	}
	
	@Override
	public void save(SubjectEntity subject){
		subjectDao.save(subject);
	}
	
	@Override
	public void update(SubjectEntity subject){
		subjectDao.update(subject);
	}
	
	@Override
	public void delete(Long dataId){
		subjectDao.delete(dataId);
	}
	
	@Override
	public void deleteBatch(Long[] dataIds){
		subjectDao.deleteBatch(dataIds);
	}

	@Override
	public List<SubjectEntity> subjectlist(Map<String, Object> params) {
		return subjectDao.subjectlist(params);
	}

    @Override
    public String getTypeIdentity(){
        return ToolClient.queryJson(subjectDao.getTypeIdentity());
    }

    @Override
    public String save(final HttpServletRequest request){
        final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
        final HashMap<String,String> formParams = ToolClient.getFormParams(request);
        final SysUserEntity user = ShiroUtils.getUserEntity();
        final String username = user.getUsername();
        if(username.equals(ConfigFile.KEY_SUPER)){
            final String validates = ToolClient.validateField(formParams,"name");
            if(validates != null) return validates;
            final String user_name = formParams.get("user_name");
            if(user_name == null){
                return ToolClient.createJsonFail("请输入经营主体的登录账号");
            }
            final HashMap<String,Object> userInfo = sysUserDao.getUserInfo(user_name);
            if(userInfo == null){
                return ToolClient.createJsonFail(user_name+"账号不存在");
            }
            final int status = (Integer)userInfo.get("status");
            if(status == 0){
                return ToolClient.createJsonFail(user_name+"账号已被禁用");
            }
            final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(user_name);
            if(subjects != null){
                return ToolClient.createJsonFail("该账号已经添加经营主体!");
            }
            formParams.put("user_id",String.valueOf(userInfo.get("user_id")));
            formParams.put("user_name",user_name);
        }else{
            final Long roleId = user.getRoleId();
            if(roleId != null && roleId == roleValue2){
                return ToolClient.createJsonFail(username+",账号类型不是经营主体!");
            }
            final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(username);
            if(subjects != null){
                return ToolClient.createJsonFail("你已经添加经营主体|请重新登录!");
            }
            formParams.put("user_id",String.valueOf(user.getUserId()));
            formParams.put("user_name",username);
        }
        final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/enterprise",1,true);
        final String errorMsg = uploadObject.getErrorMsg();
        if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
        final String validates = ToolClient.validateField(formParams,"name","identity_id","link_man","link_tel","province_id","city","county","villages");
        if(validates != null) return validates;
        final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
        final StringBuilder sb = new StringBuilder();
        for(int i = 0; i < listFiles.size(); i++){
            final String uri = listFiles.get(i).getUrlFile();
            if(sb.toString().length() > 0){
                sb.append(",").append(uri);
            }else{
                sb.append(uri);
            }
        }
        formParams.put("pic",sb.toString());
        clearArea(formParams);
        final int rows = subjectDao.saveSubject(formParams);
        if(username.equals(ConfigFile.KEY_SUPER)){
            return ToolClient.executeRows(rows);
        }else{
            if(rows > 0){
                return ToolClient.createJson(ConfigFile.code198,"操作成功,由于缓存请重新登录");
            }else{
                return ToolClient.executeRows(rows);
            }
        }
    }

    @Override
    public String update(final HttpServletRequest request){
        final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
        final SysUserEntity user = ShiroUtils.getUserEntity();
        final String username = user.getUsername();
        final HashMap<String,String> formParams = ToolClient.getFormParams(request);
        if(username.equals(ConfigFile.KEY_SUPER)){
            final String validates = ToolClient.validateField(formParams,"name");
            if(validates != null) return validates;
            final String user_name = formParams.get("user_name");
            if(user_name == null){
                return ToolClient.createJsonFail("请输入经营主体的登录账号");
            }
            final HashMap<String,Object> userInfo = sysUserDao.getUserInfo(user_name);
            if(userInfo == null){
                return ToolClient.createJsonFail(user_name+"账号不存在");
            }
            final int status = (Integer)userInfo.get("status");
            if(status == 0){
                return ToolClient.createJsonFail(user_name+"账号已被禁用");
            }
            final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(user_name);
            if(subjects == null || subjects.size() <= 0){
                return ToolClient.createJsonFail(user_name+"还没有经营主体!");
            }
        }else{
            final Long roleId = user.getRoleId();
            if(roleId != null && roleId == roleValue2){
                return ToolClient.createJsonFail(username+",账号类型不是经营主体!");
            }
            final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(username);
            if(subjects == null || subjects.size() <= 0){
                return ToolClient.createJsonFail("你还没有经营主体!");
            }
        }
        final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/enterprise",1,false);
        final String errorMsg = uploadObject.getErrorMsg();
        if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
        final String validates = ToolClient.validateField(formParams,"identity_id","link_man","link_tel");
        if(validates != null) return validates;
        final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
        if(listFiles != null){
            final StringBuilder sb = new StringBuilder();
            for(int i = 0; i < listFiles.size(); i++){
                final String uri = listFiles.get(i).getUrlFile();
                if(sb.toString().length() > 0){
                    sb.append(",").append(uri);
                }else{
                    sb.append(uri);
                }
            }
            formParams.put("pic",sb.toString());
        }
        clearArea(formParams);
        final int rows = subjectDao.editSubject(formParams);
        return ToolClient.executeRows(rows);
    }

    private void clearArea(final HashMap<String,String> formParams){
        final String province_id = formParams.get("province_id");
        if(province_id == null){
            formParams.remove("province_name");
        }
        final String city = formParams.get("city");
        if(city == null){
            formParams.remove("city_name");
        }
        final String county = formParams.get("county");
        if(county == null){
            formParams.remove("county_name");
        }
        final String villages = formParams.get("villages");
        if(villages == null){
            formParams.remove("villages_name");
        }
        final String hamlet = formParams.get("hamlet");
        if(hamlet == null){
            formParams.remove("hamlet_name");
        }
    }

    @Override
    public String queryMap(final Long id){
        return ToolClient.queryJson(subjectDao.queryMap(id));
    }
}
